package com.smcdd.cdb.dbo.cdb_dbo.ui.fragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.LocationBean;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.StoreInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.DataManager;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.SortAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseFragmentFragment;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseFragmentPresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DemoUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.map.geolocation.TencentPoi;
import com.tencent.mapsdk.raster.model.BitmapDescriptorFactory;
import com.tencent.mapsdk.raster.model.LatLng;
import com.tencent.mapsdk.raster.model.Marker;
import com.tencent.mapsdk.raster.model.MarkerOptions;
import com.tencent.tencentmap.mapsdk.map.MapView;
import com.tencent.tencentmap.mapsdk.map.TencentMap;
import com.tencent.tencentmap.mapsdk.map.UiSettings;

import java.util.Collections;
import java.util.List;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 作者：Administrator on 2017/6/23 14:20
 * 邮箱：zhanghuaiha@gmail.com
 */

public class MenDianMapFragment extends BaseFragmentFragment implements TencentLocationListener {
    private MapView mapview;
    private TencentMap map;
    private int mLevel = 2;
    private TencentLocationManager mLocationManager;
    private ImageView map_back;
    private TextView map_save;
    private Marker marker;
    private static final int LAT_LOG = 5;// 经纬度
    private DataManager manager;
    private String versionName;
    private String id;
    private CompositeSubscription mCompositeSubscription;
    private String eid;

    @Override
    public void initView(View rootView) {
        mapview=(MapView)rootView.findViewById(R.id.mapview);
        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
            if(getActivity().checkSelfPermission(permissions[0]) == PackageManager.PERMISSION_DENIED){
                requestPermissions(permissions, 0);
            }
        }

        mLocationManager = TencentLocationManager.getInstance(getActivity());
        // 设置坐标系为 gcj-02, 缺省坐标为 gcj-02, 所以通常不必进行如下调用
        // mLocationManager.setCoordinateType(TencentLocationManager.COORDINATE_TYPE_GCJ02);
        startLocation();
    }

    @Override
    public void initData() {
        manager = new DataManager(getActivity());
        versionName = ObtainVersion.getVersionName(getActivity());
        mCompositeSubscription = new CompositeSubscription();
        String time = System.currentTimeMillis() + "";
        eid = App.SP.getString("id", "");
        String udid = App.SP.getString("udid", "");
        String encry = ObtainEncry.getStoreInfo("2", time, versionName, NetWorkCodeInfo.STORE_LIST, udid, eid, "10000", "0");
        mCompositeSubscription.add(manager.getStoreList("2",time, versionName, NetWorkCodeInfo.STORE_LIST, udid, eid,"10000","0",encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<StoreInfo>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(StoreInfo storeInfo) {
                        Log.e("MenDianMapFragment",storeInfo.getCode()+"");
                        if (storeInfo.getCode() == 200) {
                            List<StoreInfo.DataBean> data = storeInfo.getData();
                            for (int i = 0; i < data.size(); i++) {
                                double lat = Double.parseDouble(data.get(i).getLatitude());
                                double log = Double.parseDouble(data.get(i).getLongitude());
                                if (data.get(i).getStatus().equals("1")) {
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng(lat,log))
                                            .anchor(0.5f, 0.5f)
                                            .title(data.get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.mipmap.yipushe))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else {
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng(lat,log))
                                            .anchor(0.5f, 0.5f)
                                            .title(data.get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.mipmap.weipushe))
                                            .draggable(true));
                                    marker.setVisible(true);
                                    marker.isInfoWindowShown();
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }
                            }
                        }
                    }
                }));
    }

    @Override
    protected BaseFragmentPresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_map;
    }


    @Override
    public void onDestroy() {
        mapview.onDestroy();
        if (mCompositeSubscription.hasSubscriptions()){
            mCompositeSubscription.unsubscribe();
        }
        super.onDestroy();
    }

    @Override
    public void onPause() {
        mapview.onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mapview.onResume();
        super.onResume();
    }

    @Override
    public void onStop() {
        mLocationManager.removeUpdates(this);
        mapview.onStop();
        super.onStop();
    }


    private void ininData(LocationBean locationBean) {
        map = mapview.getMap();
        map.setCenter(new LatLng(locationBean.getLat(),locationBean.getLog()));
        map.setZoom(15);

        //获取UiSettings实例
        UiSettings uiSettings = mapview.getUiSettings();
        //设置logo到屏幕底部中心
        uiSettings.setLogoPosition(UiSettings.LOGO_POSITION_CENTER_BOTTOM);
        //设置比例尺到屏幕右下角
        uiSettings.setScaleViewPosition(UiSettings.SCALEVIEW_POSITION_RIGHT_BOTTOM);

        marker = mapview.addMarker(new MarkerOptions()
                .position(new LatLng(locationBean.getLat(),locationBean.getLog()))
                .anchor(0.5f, 0.5f)
                .title("当前位置")
                .icon(BitmapDescriptorFactory
                        .defaultMarker())
                .draggable(true));
        marker.showInfoWindow();// 设置默认显示一个infoWindow
        marker.hideInfoWindow();

    }



    // 响应点击"开始"
    public void startLocation() {
        // 创建定位请求
        TencentLocationRequest request = TencentLocationRequest.create()
                .setInterval(5000) // 设置定位周期
                .setAllowGPS(true)  //当为false时，设置不启动GPS。默认启动
                .setAllowIndoorLocation(true)  //设置启动室内定位，默认不启动
                .setQQ("10001")
                .setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA); // 设置定位level

        // 开始定位
        mLocationManager.requestLocationUpdates(request, this);

        Log.e("mappp", DemoUtils.toString(mLocationManager.getCoordinateType()));
    }



    @Override
    public void onLocationChanged(TencentLocation location, int error, String s) {
        LocationBean locationBean = null;
        if (error == TencentLocation.ERROR_OK) {
            // 定位成功
            locationBean = toString(location, TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA);
        } else {
            // 定位失败
            String msg = "定位失败: " + s;
            locationBean = new LocationBean();
            locationBean.setName(msg);
        }
        updateLocationStatus(locationBean);
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }

    // ====== location callback

    private void updateLocationStatus(LocationBean locationBean) {
        mLocationManager.removeUpdates(this);
        ininData(locationBean);
        Log.e("map",locationBean.getName());

    }


    // ===== util method
    private static LocationBean toString(TencentLocation location, int level) {
        StringBuilder sb = new StringBuilder();
        if (location.getLatitude() != 0.0 && location.getLongitude() != 0.0) {
            LocationBean locationBean = new LocationBean();
            locationBean.setLat(location.getLatitude());
            locationBean.setLog(location.getLongitude());
            locationBean.setName("获取定位成功");
            return locationBean;
        }

        sb.append("latitude=").append(location.getLatitude()).append(",");
        sb.append("longitude=").append(location.getLongitude()).append(",");
        sb.append("altitude=").append(location.getAltitude()).append(",");
        sb.append("accuracy=").append(location.getAccuracy()).append(",");
        sb.append("indoorBuildingId=").append(location.getIndoorBuildingId()).append(",");
        sb.append("indoorBuildingFloor=").append(location.getIndoorBuildingFloor()).append(",");

        switch (level) {
            case TencentLocationRequest.REQUEST_LEVEL_GEO:
                break;

            case TencentLocationRequest.REQUEST_LEVEL_NAME:
                sb.append("name=").append(location.getName()).append(",");
                sb.append("address=").append(location.getAddress()).append(",");
                break;

            case TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA:
            case TencentLocationRequest.REQUEST_LEVEL_POI:
            case 7:
                sb.append("nation=").append(location.getNation()).append(",");
                sb.append("province=").append(location.getProvince()).append(",");
                sb.append("city=").append(location.getCity()).append(",");
                sb.append("district=").append(location.getDistrict()).append(",");
                sb.append("town=").append(location.getTown()).append(",");
                sb.append("village=").append(location.getVillage()).append(",");
                sb.append("street=").append(location.getStreet()).append(",");
                sb.append("streetNo=").append(location.getStreetNo()).append(",");

                if (level == TencentLocationRequest.REQUEST_LEVEL_POI) {
                    List<TencentPoi> poiList = location.getPoiList();
                    int size = poiList.size();
                    for (int i = 0, limit = 3; i < limit && i < size; i++) {
                        sb.append("\n");
                        sb.append("poi[" + i + "]=")
                                .append(toString(poiList.get(i))).append(",");
                    }
                }

                break;

            default:
                break;
        }

        return null;
    }

    private static String toString(TencentPoi poi) {
        StringBuilder sb = new StringBuilder();
        sb.append("name=").append(poi.getName()).append(",");
        sb.append("address=").append(poi.getAddress()).append(",");
        sb.append("catalog=").append(poi.getCatalog()).append(",");
        sb.append("distance=").append(poi.getDistance()).append(",");
        sb.append("latitude=").append(poi.getLatitude()).append(",");
        sb.append("longitude=").append(poi.getLongitude()).append(",");
        return sb.toString();
    }
}
